import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { HomeModule } from './home/home.module';
import { UserModule } from './user/user.module';
import { UploadModule } from './upload/upload.module';
import { LoggerModule } from './log/logger.module';
import { transports, format } from 'winston';
import { TypeOrmModule} from '@nestjs/typeorm';
import * as chalk from 'chalk';
import { JwtModule } from '@nestjs/jwt';
import { RedisModule } from './redis/redis.module';
import { ConfigModule } from '@nestjs/config';
import config01 from './config/config01'


// 作为动态模块引入日志
const WinstonModule = LoggerModule.forRoot({
  level: 'debug',
  transports: [
      new transports.Console({
          format: format.combine(
              format.colorize(),
              format.printf(({context, level, message, time}) => {
                  const appStr = chalk.green(`[NEST]`);
                  const contextStr = chalk.yellow(`[${context}]`);

                  return `${appStr} ${time} ${level} ${contextStr} ${message} `;
              })
          ),

      }),
      new transports.File({
          format: format.combine(
              format.timestamp(),
              format.json()
          ),
          filename: `${new Date().getFullYear()}-${new Date().getMonth() + 1}-${new Date().getDay()}.log`,
          dirname: 'log'
      })
  ]
})

// 作为动态模块引入sql
const SqlModule = TypeOrmModule.forRoot({
  type: "mysql", //数据库类型
  username: config01().db.username, //账号
  password: config01().db.password, //密码
  host: "localhost", //host
  port: config01().db.port, //
  database: config01().db.database, //库名
  entities: [__dirname + '/**/*.entity{.ts,.js}'], // 关联的实体文件
  synchronize: true, //synchronize字段代表是否自动将实体类同步到数据库
  retryDelay: 500, //重试连接数据库间隔
  retryAttempts: 10,//重试连接数据库的次数
  autoLoadEntities: true, //如果为true,将自动加载实体 forFeature()方法注册的每个实体都将自动添加到配置对象的实体数组中
  logging: true
})

// 动态引入
const JwtModuleDaynamic = JwtModule.register({
  global: true,
  secret: 'helloworld',
  signOptions: {
    expiresIn: '30m'
  }
})

// 参数引入
const ConfigModuleDaynamic = ConfigModule.forRoot({
  load: [config01]
})

@Module({
  imports: [ConfigModuleDaynamic ,WinstonModule, SqlModule, JwtModuleDaynamic, HomeModule, UserModule, UploadModule, RedisModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
